<?php
class SearchComponent extends Object {

  
  	var $controller = null;
 	var $components = array('Redirect');
	function initialize(&$controller, $config)
	{
	    $this->controller = $controller;
	}
	    	
	function startup() {
	}
	
	function redirectDataSearch($controllername,$data){
		// the page we will redirect to

		$url['controller'] = strtolower($controllername->name);
		$url['action'] = 'search';
		
		// build a URL will all the search elements in it
		// the resulting URL will be
		// example.com/cake/posts/index/Search.keywords:mykeyword/Search.tag_id:3
		foreach ($data as $k=>$v){
			foreach ($v as $kk=>$vv){
				$url[$k.'.'.$kk]=$vv;
			}
		}
		// redirect the user to the url
		$this->controller->redirect($url, null, true);
	}
	
	function doSearch($controllername, $passedArgs){
		$conditions = array();
		$singularName = ucfirst(Inflector::humanize(Inflector::underscore(Inflector::singularize($controllername->name))));
		if (!empty($passedArgs))
		{
			if (isset($passedArgs['Search.name']))
			{
				$conditions[][$singularName.".name LIKE"] = "%{$passedArgs['Search.name']}%";
				$controllername->data['Search']['name'] = $passedArgs['Search.name'];
			}
			$controllername->paginate = array('limit' => '1', 'order' => $singularName.'.created DESC');
			$result=$controllername->paginate($singularName, $conditions);

			if(count($result)>0){
				$controllername->set(strtolower($controllername->name), $result);
			} else {
				$controllername->Redirect->flashWarning('Data not found');				
			}	
		}
	}	

}
